package org.smart4j.chapter4.threadLocal.example;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.text.SimpleDateFormat;
import java.util.Date;

public class ProductServiceImpl implements ProductService {

    private static final String UPDATE_PRODUCT_SQL = "update product set price = ? where id = ?";
    private static final String INSERT_LOG_SQL = "insert into log (created, description) values (?, ?)";

    @Override
    public void updateProductPrice(long productId, int price) {
        try {
            //获取连接
            Connection conn = DBUtil.getConnection();
            //关闭自动提交（开启事务）
            conn.setAutoCommit(false);

            //执行操作
            updateProduct(conn, UPDATE_PRODUCT_SQL, productId, price);
            insertLog(conn, INSERT_LOG_SQL, "update product:" + productId);

            //提交事务
            conn.commit();
        } catch (Exception e){
            e.printStackTrace();
        } finally {
            DBUtil.closeConnection();
        }
    }

    //更新产品价格
    private void updateProduct(Connection conn, String sql, long id, int price) throws Exception{
        PreparedStatement preparedStatement = conn.prepareStatement(sql);
        preparedStatement.setInt(1, price);
        preparedStatement.setLong(2, id);
        int rows = preparedStatement.executeUpdate();
        if (rows != 0){
            System.out.println("update produce success!");
        }
    }

    //插入日志记录
    private void insertLog(Connection conn, String sql, String logDescription) throws Exception{
        PreparedStatement preparedStatement = conn.prepareStatement(sql);
        preparedStatement.setString(1, new SimpleDateFormat("yyyy-MM-dd HH:mm:ss SSS").format(new Date()));
        preparedStatement.setString(2, logDescription);
        int rows = preparedStatement.executeUpdate();
        if (rows != 0){
            System.out.println("insert log success!");
        }
    }

    public static void main(String[] args) {
        for (int i = 0; i < 10; i++){
            ProductService productService = new ProductServiceImpl();
            ProductChilentThread thread = new ProductChilentThread(productService);
            thread.start();
        }


    }
}
